//
//  QJHomeVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/1/30.
//  Copyright © 2018年 apple. All rights reserved.
//

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>


#import "QJHomeVC.h"
#import "QJMineInforVC.h"
#import "QJLoginVC.h"
#import "QJCategoryVC.h"
#import "YFNearVC.h"
#import "QJMineVC.h"

#import "YFNavigationTopView.h"
//数据为空
#import "UIScrollView+EmptyDataSet.h"

//第二类分区
#import "YFHomeZeroCell.h"
#import "YFHomeOneCell.h"

//其他分类的界面
#import "QJHomeVCClassVC.h"
//商品详情
#import "QJShopDetailVC.h"
//开店
#import "QJKaiDianVC.h"
//二维码扫描
#import "QJCoreScanVC.h"
//收款
#import "QJShouKuanVC.h"

// TopView
#import "YFSearchBar.h"
#import "YFArrowButton.h"
#import "YFSelectCityView.h"

#import "YFHomeOneReusableView.h"
#import "YFHomeZeroReusableView.h"
#import "YFWebViewController.h"
#import "YFShopRegisterVC.h"
#import "YFIntegralAreaViewController.h"
#import "ScoreVC.h"
@interface QJHomeVC () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>{
    int _page;
    BMKLocationService* _locService;
    BMKGeoCodeSearch* _geocodesearch;
    CLLocationCoordinate2D _myCoordinate;
}
@property (nonatomic, strong) UICollectionView *homeCollectionView;
@property (nonatomic, strong) YFHomeZeroReusableView *zeroHeader;

@property (nonatomic, strong) YFNavigationTopView *topView;
@property (nonatomic, strong) YFSelectCityView *selectCityView;

// 数据源
@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) NSMutableArray *bigArray;
@property (nonatomic, strong) NSMutableArray *smallArray;
@property (nonatomic, strong) NSMutableArray *loopArray;
@property (nonatomic, strong) NSMutableArray *goodsListArray;

@end

@implementation QJHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = YFColor_Background;
    [self.view addSubview:self.topView];
    //界面布局
    [self setupHomeView];
    [self dataRequestHomeAction];
    self.extendedLayoutIncludesOpaqueBars = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.topView updateCircleImage]; // 登陆返回按钮没变
    
    [self startLocationService];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(permissionSuccess) name:@"PermissionSuccess" object:nil];
    
    [self setNavAlpha:YES];
    self.navigationController.navigationBarHidden = YES;
    
    _page = 1;
   
    
//    [self dataRequestCityAction];
    
    [self.zeroHeader.loopView startTimer];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self setNavAlpha:NO];
    self.navigationController.navigationBarHidden = NO;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"PermissionSuccess" object:nil];
    
    [self.zeroHeader.loopView stopTimer];
}

#pragma mark -- 百度地图相关
//处理方向变更信息
//- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
//{
//    KMyLog(@"heading is %@",userLocation.heading);
//}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    KMyLog(@"latitude = %f, longitude = %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    _myCoordinate = userLocation.location.coordinate;
    
    [_locService stopUserLocationService]; // 之前是注释的, 现在打开
    
    // 是否允许应用访问位置,点击确定后,只调用了 didUpdateBMKUserLocation, 手动反编码
    [self permissionSuccess];
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
    
    
}


// 百度地图授权成功
- (void)permissionSuccess {
    //*
    //初始化检索对象
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    //发起反向地理编码检索
//    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){36.569349, 114.216992};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = _myCoordinate;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        KMyLog(@"反geo检索发送成功");
    }
    else
    {
        KMyLog(@"反geo检索发送失败");
    }
    //*/
    
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
//    KMyLog(@"address = %@, cityCode = %@, city = %@", result.address, result.cityCode, result.addressDetail.city);
    // 定位提醒
    if (![result.cityCode isEqualToString:@"0"] && (result.cityCode.length != 0)) { // 等于0 是无效的回调
        // 去除"市"
        
        NSString *city = result.addressDetail.city;
        [self.topView.leftBtn setTitle:city forState:UIControlStateNormal];
        
    }
    
}


- (void)startLocationService{
    
//    KMyLog(@"[CLLocationManager locationServicesEnabled] = %zd", [CLLocationManager locationServicesEnabled]);
    
    //允许PGS访问定位
    //            [_locationService startUserLocationService];
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _locService.distanceFilter = 100;
    //    _locService.pausesLocationUpdatesAutomatically = NO;
    //    _locService.allowsBackgroundLocationUpdates = YES;
    //启动LocationService
    [_locService startUserLocationService];
}

#pragma mark -- 界面布局
- (void)setupHomeView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    //滚动方向(默认垂直)
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.homeCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topView.frame), UISCREEN_WIDTH, UISCREEN_HEIGHT - self.topView.frame.size.height - Height_TabBar) collectionViewLayout:layout]; // 49 是tabbar的高度

    [self.view addSubview:self.homeCollectionView];
    self.homeCollectionView.delegate = self;
    self.homeCollectionView.dataSource = self;
    self.homeCollectionView.emptyDataSetDelegate = self;
    self.homeCollectionView.emptyDataSetSource = self;
    self.homeCollectionView.backgroundColor = YFColor_Background;
    //在cell的个数不多的时候也可以竖直滑动
    self.homeCollectionView.alwaysBounceVertical = YES;
    
    // 不用Xib,用代码实现
    [self.homeCollectionView registerClass:[YFHomeZeroReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerOne"];
    [self.homeCollectionView registerClass:[YFHomeOneReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerTwo"];

    //cell
    [self.homeCollectionView registerClass:[YFHomeZeroCell class] forCellWithReuseIdentifier:@"cellOne"];
    [self.homeCollectionView registerClass:[YFHomeOneCell class] forCellWithReuseIdentifier:@"cellTwo"];
    // 刷新
//    self.homeCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HRefresh)];
    
    self.homeCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshNear)];
    self.homeCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshNear)];
}
#pragma mark -- 数据刷新
- (void)headerRefreshNear{
    _page = 1;
    [self dataRequestHomeAction];
}
- (void)footerRefreshNear{
    _page++;
    [self dataRequestHomeAction];
}
#pragma mark -- 数据请求
- (void)dataRequestHomeAction{
    [self.homeCollectionView.mj_footer endRefreshing];
    [self.homeCollectionView.mj_header endRefreshing];
    
    NSNumber *pageNum = [NSNumber numberWithInt:_page];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:pageNum forKey:@"p"];
    
    [WWNetRequest fetchHomeWithParameters:dict success:^(id response) {
        
        NSLog(@"首页response = %@", response);
        NSArray *banner = response[@"ad_banner"];
        NSArray *loopArr = response[@"article"];
        NSArray *bigArr = response[@"ad_big"];
        NSArray *smallArr = response[@"ad_small"];
        NSArray *goodListArr = response[@"goods_list"];
        
        
        [self.bigArray removeAllObjects];
        [self.smallArray removeAllObjects];
        [self.loopArray removeAllObjects];
        [self.bannerArray removeAllObjects];
        // 大图
        for (NSDictionary *dict in bigArr) {
            HomeBigSmallModel *model = [[HomeBigSmallModel alloc]initWithDictionary:dict error:nil];
            [self.bigArray addObject:model];
        }
        // 小图
        for (NSDictionary *dict in smallArr) {
            HomeBigSmallModel *model = [[HomeBigSmallModel alloc]initWithDictionary:dict error:nil];
            [self.smallArray addObject:model];
        }
        // 滚动图
        for (NSDictionary *dic  in loopArr) {
            HomeLoopModel *model = [[HomeLoopModel alloc]initWithDictionary:dic error:nil];
            [self.loopArray addObject:model];
        }
       
        // 轮播图
        
        for (NSDictionary *dict in banner) {
            HbannerModel *model = [[HbannerModel alloc]initWithDictionary:dict error:nil];
//            NSLog(@"ad_code = %@", model.ad_code);
            [self.bannerArray addObject:model];
        }
        
        // 商品列表
        NSMutableArray *tempGoodListArr = [NSMutableArray array];
        for (NSDictionary *dict in goodListArr) {
            // 这里先用SearchMdoel ,后期再改名字
            SearchMdoel *model = [[SearchMdoel alloc]initWithDictionary:dict error:nil];
//            NSLog(@"goods_name = %@", model.goods_name);
            [tempGoodListArr addObject:model];
        }
        
        if (_page == 1) {
            [self.goodsListArray removeAllObjects];
            self.goodsListArray = tempGoodListArr;
        }else {
            for (SearchMdoel *model in tempGoodListArr) {
                [self.goodsListArray addObject:model];
            }
        }
        //刷新数据
        [self.homeCollectionView reloadData];
        
    } failure:^(NSDictionary *error) {
        
    }];
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.goodsListArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YFHomeOneCell *oneCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellTwo" forIndexPath:indexPath];
    [oneCell cellUpdateWithModel:self.goodsListArray[indexPath.row]];
    return oneCell;
}
#pragma mark --  区头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        //区头
        YFHomeZeroReusableView *zeroHeader = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerOne" forIndexPath:indexPath];

        [zeroHeader setHeaderWithBannerArray:self.bannerArray LoopArray:self.loopArray BigArray:self.bigArray smallArray:self.smallArray];
        zeroHeader.registerUnderLineBlock = ^{ // 积分专区
            
            ScoreVC *scorevc = [[ScoreVC alloc] init];
            KPushViewControllerAction(scorevc);
            
        };
        zeroHeader.headerBtnClickBlock = ^(NSInteger tag) {  // 十个按钮点击
            [weakSelf headerBtnClickActionWithTag:tag];
        };
        zeroHeader.clickItemOperationBlock = ^(NSInteger currentIndex) { // 轮播图
    //                    NSLog(@"currentIndex = %d", currentIndex);
            HbannerModel *model = _bannerArray[currentIndex];
            if ([model.status intValue] == 0) { // 0:不跳转
            }else if ([model.status intValue] == 1) {  // 1:商品页
                
                QJShopDetailVC *VC = [QJShopDetailVC new];
                VC.goodsID = [NSString stringWithoutNilFormart:model.goods_id];
                KPushViewControllerAction(VC);
                
            }else if ([model.status intValue] == 2) {  // 2:商家入驻
                YFShopRegisterVC *registerVC = [[YFShopRegisterVC alloc] init];
                KPushViewControllerAction(registerVC);
                
            }else if ([model.status intValue] == 3) {  // 3:跳转linkurl
                NSString *url = [NSString stringWithFormat:@"%@%@",NET_BASEURL,model.ad_link];
                
                YFWebViewController *vc = [[YFWebViewController alloc] init];
                vc.urlString = url;
                KPushViewControllerAction(vc);
            }
        };
        self.zeroHeader = zeroHeader;
        return zeroHeader;
    }else{
        //区尾
        return nil;
    }
}
#pragma mark -- UICollectionViewDelegate
#pragma mark -- 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    QJShopDetailVC *VC = [QJShopDetailVC new];
    SearchMdoel *model = self.goodsListArray[indexPath.row];
    VC.goodsID = [NSString stringWithoutNilFormart:model.goods_id];
    KPushViewControllerAction(VC);
}
#pragma mark - UICollectionViewDelegateFlowLayout -
//定义每个item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat padding = 1;
    CGFloat w = (UISCREEN_WIDTH - padding*2)/2;
    CGFloat h = w * 550.f/370.f;  // 520.f/370.f;
    return CGSizeMake(w, h);
}
#pragma mark -- item的缩进量
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
#pragma mark -- 设置单元格的横向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
#pragma mark -- 设置单元格的纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section{
   return 1.0f;
}
#pragma mark -- 区头的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    YFHomeZeroReusableView *testView= [[YFHomeZeroReusableView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, 0)];
    
    return CGSizeMake(UISCREEN_WIDTH, 950+ (self.topView.frame.size.height));
}

#pragma mark
#pragma mark -- 顶部功能按钮点击事件

- (void)jumpToCategoryVC {
    QJCategoryVC *vc = [[QJCategoryVC alloc] init];
    KPushViewControllerAction(vc);
}
- (void)headerBtnClickActionWithTag:(NSInteger)tag{

    switch (tag) {
        case ZeroTagClothing:  // 服装
            [self jumpToVCWithClassID:@"5"];
            break;
        case ZeroTagHealthy:   // 健康
            [self jumpToVCWithClassID:@"1"];
            break;
        case ZeroTagWine:    // 酒水
            [self jumpToVCWithClassID:@"4"];
            break;
        case ZeroTagFood:  // 美食
            [self jumpToVCWithClassID:@"2"];
            break;
        case ZeroTagChildren:  // 母婴儿童
            [self jumpToVCWithClassID:@"37"];
            break;
        case ZeroTaglectricalAppliances:  // 家电
            [self jumpToVCWithClassID:@"7"];
            break;
        case ZeroTagGoods:  // 日用百货
            [self jumpToVCWithClassID:@"31"];
            break;
        case ZeroTagHaircut:  // 美妆
            [self jumpToVCWithClassID:@"8"];
            break;
        case ZeroTagKitchen:   // 厨具
            [self jumpToVCWithClassID:@"40"];
            break;
        case ZeroTagCar:    // 汽车用品
            [self jumpToVCWithClassID:@"38"];
            break;
        default:
            break;
    }
}
#pragma mark -- 根据不同的id跳转不同的界面
- (void)jumpToVCWithClassID:(NSString *)classID{
    QJHomeVCClassVC *VC = [[QJHomeVCClassVC alloc]init];
    VC.type = @"1";
    VC.classID = classID;
    KPushViewControllerAction(VC);
}

#pragma mark -- 私有点击方法

#pragma mark -- 懒加载
-(NSMutableArray *)bannerArray{
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}

-(NSMutableArray *)bigArray{
    if (!_bigArray) {
        _bigArray = [NSMutableArray array];
    }
    return _bigArray;
}
-(NSMutableArray *)smallArray{
    if (!_smallArray) {
        _smallArray = [NSMutableArray array];
    }
    return _smallArray;
}
-(NSMutableArray *)loopArray{
    if (!_loopArray) {
        _loopArray = [NSMutableArray array];
    }
    return _loopArray;
}
-(NSMutableArray *)goodsListArray{
    if (!_goodsListArray) {
        _goodsListArray = [NSMutableArray array];
    }
    return _goodsListArray;
}

- (UIView *)topView {
    if (!_topView) {
        YFNavigationTopView *topView = [[YFNavigationTopView alloc] initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, Height_NavBar)];
        topView.hiddenLeftButton = YES;
        _topView = topView;
        kWeakSelf
        topView.rightBtnClick = ^{  // 个人中心点击            
            
            QJCategoryVC *VC = [[QJCategoryVC alloc] init];
            KPushViewControllerAction(VC);
            
            // 测试  积分专区
//            YFIntegralAreaViewController *VC = [[YFIntegralAreaViewController alloc] init];
//            KPushViewControllerAction(VC);
            // 测试结束
        };
        
        topView.leftBtnClick = ^{ // 定位
            if (weakSelf.selectCityView.isShowing) { // 显示
                [weakSelf.selectCityView hidden];
            }else { // 隐藏
                [weakSelf.selectCityView show];
            }
        };
        
        topView.textFieldClick = ^{  // 搜索框
            QJHomeVCClassVC *VC = [[QJHomeVCClassVC alloc]init];
            KPushViewControllerAction(VC);
        };
        

        topView.codeClick = ^{ // 扫一扫
            if ([QJUserInfo isLogin]) {
                QJCoreScanVC *VC = [[QJCoreScanVC alloc]init];
                KPushViewControllerAction(VC);
            }else{
                [MBPHUD showAlertWithTitle:@"您还没有登录,请去登录!"];
            }
        };

        [self.view addSubview:topView];
        
    }
    return _topView;
}

- (YFSelectCityView *)selectCityView {
    if (!_selectCityView) {
        _selectCityView = [[YFSelectCityView alloc] init];
        kWeakSelf;
        _selectCityView.didSelectRow = ^(CityModel *cityModel) {
            [weakSelf.topView.leftBtn setTitle:cityModel.name forState:UIControlStateNormal];
        };
        [self.view addSubview:_selectCityView];
        [self.view bringSubviewToFront:_selectCityView];
    }
    return _selectCityView;
}



@end
